package pub.tbc.api.helper;

import lombok.extern.slf4j.Slf4j;
import pub.tbc.api.service.ServiceConfigTable;

import java.util.Optional;
import java.util.Set;

/**
 * Service助手类
 *
 * @author tbc on 2017/3/22 12:21:59.
 */
@Slf4j
public class ServiceHelper {

    /**
     * 根据uri获取服务名
     *
     * @param uri 请求uri
     * @return 服务名
     */
    public static String getServiceNameByUri(String uri) {
        String path = uri.startsWith("/") ? uri.substring(1, uri.length()) : uri;
        int index = !path.contains("/") ? path.length() : path.indexOf("/", 1);
        path = path.substring(0, index);
        index = !path.contains("?") ? index : path.indexOf("?", 1);
//        if (config.get("ignoreCase")) return serviceNameAdapter(path.substring(0, index))
        // 此处先写死，进行忽略大小写适配获取服务名
        return serviceNameAdapter(path.substring(0, index));
    }

    /**
     * 服务名大小写适配<br>
     * 1. 如果映射表中的key集合包含原服务名，说明不需要适配，直接返回；<br>
     * 2. 如果不包含，则遍历映射表Key集合，使用equalsIgnoreCase方法忽略大小写进行匹配；<br>
     * 3. 若找到匹配值，该值就是适配的服务名，返回；<br>
     * 4. 若找不到匹配值，说明该服务未配置，直接返回原服务名；<br>
     *
     * @param serviceName 原始服务名
     * @return 适配后(适配为跟映射表中一致)服务名
     */
    public static String serviceNameAdapter(String serviceName) {
        ServiceConfigTable configTable = ServiceConfigTable.getInstance();
        Set<String> keySet = configTable.getServiceMap().keySet();
        if (keySet.contains(serviceName)) return serviceName;
        Optional<String> optional = keySet.stream()
                .filter(serviceName::equalsIgnoreCase)
                .findFirst();
        return optional.orElse(serviceName);
    }

    public static String serviceNameAdapter0(String serviceName) {
        ServiceConfigTable configTable = ServiceConfigTable.getInstance();
        Set<String> keySet = configTable.getServiceMap().keySet();
        return keySet.contains(serviceName) ? serviceName :
                keySet.stream()
                        .filter(serviceName::equalsIgnoreCase)
                        .findFirst()
                        .orElse(serviceName);
    }
}
